package com.icloud.cer.rest.util;

public class StringUtils {
	public static final String EMPTY = "";

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}

	/**
	 * 将异常信息中的摘要输出到StringBuilder中
	 * 
	 * @param e
	 * @param sb
	 */
	public static void exceptionSummary(Throwable e, StringBuilder sb) {
		String msg = e.getLocalizedMessage();
		StackTraceElement[] stacks = e.getStackTrace();
		if (msg == null && e.getCause() != null) {
			exceptionSummary(e.getCause(), sb);
		}
		String stack = stacks.length > 0 ? stacks[0].toString() : "";
		sb.append(e.getClass().getSimpleName()).append(':').append(msg)
				.append('\n').append(stack);
	}

	/**
	 * 返回异常信息的堆栈摘要
	 * 
	 * @param e
	 * @return
	 */
	public static String exceptionSummary(Throwable e) {
		String msg = e.getLocalizedMessage();
		StackTraceElement[] stacks = e.getStackTrace();
		if (msg == null && e.getCause() != null) {
			msg = exceptionSummary(e.getCause());
		}
		String stack = stacks.length > 0 ? stacks[0].toString() : "";
		return StringUtils.concat(e.getClass().getSimpleName(), ":", msg,
				"\r\n", stack);
	}

	public static String getTrace(Exception e) {
		StackTraceElement[] traces = e.getStackTrace();
		if (traces != null && traces.length > 0) {
			return e.getClass().getSimpleName() + "\n" + traces[0];
		}
		return e.getClass().getSimpleName();
	}

	public static String concat(String... args) {
		if (args.length == 1)
			return args[0];
		int n = 0;
		for (String s : args) {
			if (s == null)
				continue;
			n += s.length();
		}
		StringBuilder sb = new StringBuilder(n);
		for (String s : args) {
			if (s == null)
				continue;
			sb.append(s);
		}
		return sb.toString();
	}

	public static String join(Object[] array, String separator, int startIndex,
			int endIndex) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = EMPTY;
		}

		// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) +
		// len(separator))
		// (Assuming that all Strings are roughly equally long)
		int bufSize = (endIndex - startIndex);
		if (bufSize <= 0) {
			return EMPTY;
		}

		bufSize *= ((array[startIndex] == null ? 16 : array[startIndex]
				.toString().length()) + separator.length());

		StringBuffer buf = new StringBuffer(bufSize);

		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(array[i]);
			}
		}
		return buf.toString();
	}

}
